package Utils;/*
 *  @Author Mr.long
 *  @QQ 1507468405
 *  @Creat 2021/11/7 - 21:53
 */

import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;

public class MyExcel {
    public MyExcel() {
    }

    public void exportData(JSONObject json, String filePath,String filename) throws IOException, JSONException {
//        创建HSSFWorkBook对象
        HSSFWorkbook sheets = new HSSFWorkbook();
//        创建Sheet对象
        HSSFSheet sheet = sheets.createSheet("userList");

//        写第0行，就是标题
        HSSFRow rowTitle = sheet.createRow(0);
        //写入表头
        JSONArray title = json.getJSONArray("TableTitle");
        rowTitle.createCell(0).setCellValue(title.length());
        //列数
        int colNum = title.length();
        for (int i = 0; i < colNum; i++) {
            HSSFCell cell = rowTitle.createCell(i);
//            设置单元格的值
            cell.setCellValue((String) title.get(i));
        }
//        写入数据
        JSONArray userList = json.getJSONArray("TableList");
        for (int i = 1; i < userList.length()+1; i++) {
//            创建行
            HSSFRow row = sheet.createRow(i);
            int j = 0;
            JSONObject object = (JSONObject)userList.get(i - 1);
            //通过表头来获取值
            for(int k = 0; k < colNum;k++){
                //设置自动列宽
                sheet.autoSizeColumn(j);
                HSSFCell cell = row.createCell(j);
//                设置单元格的值
                cell.setCellValue(object.getString(title.getString(k)));
                j++;
            }
            /*Iterator jsonIt = object.keys();
            while (jsonIt.hasNext()){
               String next =  (String)jsonIt.next();
               sheet.autoSizeColumn(j);
                HSSFCell cell = row.createCell(j);
//                设置单元格的值
                cell.setCellValue(object.getString(next));
                j++;
            }*/
        }
        File path = new File(filePath);
        if(!path.exists()){
            path.mkdirs();
        }
        filename = path+File.separator+filename;
        FileOutputStream fos = new FileOutputStream(filename);
        sheets.write(fos);
        fos.flush();
        fos.close();
    }
}
